<template>
  <q-previewImage v-show="isPreviewProduct" class="z-19000" ref="previewProductImage"
    :urls="[currentRecord.skuImageUrl || defaultImg]"></q-previewImage>
  <q-previewImage v-show="isPreviewDelivery" class="z-19000" ref="previewDeliveryImage"
    :urls="[currentRecord.skuImageUrl || defaultImg]"></q-previewImage>
  <q-previewImage v-show="isPreviewChange" class="z-19000" ref="previewChangeImage"
    :urls="[currentRecord.skuImageUrl || defaultImg]"></q-previewImage>
  <q-previewImage v-show="isPreviewBackContract" class="z-19000" ref="previewBackContractImage"
    :urls="[detail.backContractUrl || defaultImg]"></q-previewImage>
  <view class="order-detail-page p-32rpx flex flex-col h-full box-border">
    <view class="flex-1 overflow-auto" style="min-height: 0;">
      <view class="detail-box detail-border h-131px flex flex-col justify-between ">
        <view class="flex justify-center">
          <view
            :class="`order-state px-16rpx py-4rpx  border-rd-11px text-#fff vertical-middle ${detail?.poStateBgColor}`">
            {{ stateMap.get(detail.poState) }}</view>
          <view class="order-state flex items-center px-16rpx py-4rpx border-rd-11px text-#fff ml-16rpx text-24rpx"
            v-if="detail.poState !== 6 && detail.poState !== 7 && (detail?.paymentSign === 1 || detail?.paymentSign === 2) && (detail?.paymentType === 1 || detail?.paymentType === 2)"
            style="background-color: #34C759;">
            <up-icon name="star-fill" color="#fff" size="12"></up-icon>
            {{ detail?.paymentSign === 1 ? `已付款` : '已结清' }}
          </view>
        </view>
        <!-- 待确认 -->
        <view v-if="detail.poState === 1" class="flex justify-center">
          <view class="vertical-middle text-24rpx text-#6B7280">请在 <span class="text-#F53F3F">{{ countdownStr }}</span>
            内确认该订单</view>
        </view>
        <view v-if="detail.poState !== 1 && detail.poStateTip" class="flex justify-center">
          <view class="vertical-middle text-24rpx text-#6B7280">{{ detail.poStateTip }}</view>
        </view>
        <view class="flex justify-center">
          <view class="text-28px font-700">{{ detail.poCurrency?.unitSymbol }}{{ thousandSeparatFormat(detail?.poPrice
            || '') }}({{ detail?.poPcs || ''
            }}pcs)</view>
        </view>
        <view class="flex justify-center">
          <view class="text-16px">总金额</view>
        </view>
      </view>
      <view class="detail-box detail-border">
        <view class="flex mb-24rpx">
          <view class="min-w-260rpx ">收货地（{{ detail?.storeName || '' }}）:</view>
          <view>
            <view class="">{{ detail?.receiverName || '' }}({{ detail?.receiverPhone || '' }})</view>
            <view class="text-#86909C">({{ detail?.storeName || '' }}){{ detail?.receiverAddress || '' }}</view>
          </view>
        </view>
        <view class="flex mb-24rpx">
          <view class="min-w-260rpx ">银行账户</view>
          <view>
            <view class="">{{ detail?.openBank || '' }}</view>
            <view class="text-#86909C">{{ detail?.bankAccount || '' }}</view>
          </view>
        </view>
        <view class="flex mb-24rpx">
          <view class="min-w-260rpx">跟单员:</view>
          <view class="text-#86909C">{{ detail?.tracker || '' }}</view>
        </view>
        <view class="flex mb-24rpx">
          <view class="min-w-260rpx">到仓货期:</view>
          <view class="text-#86909C">{{ detail?.requestDeliveryTime || '' }}</view>
        </view>
        <view class="flex mb-24rpx">
          <view class="min-w-260rpx">创建时间:</view>
          <view class="text-#86909C">{{ detail?.createdTime || '' }}</view>
        </view>
        <view class="flex mb-24rpx">
          <view class="min-w-260rpx">点击查看并下载:</view>
          <view>
            <view class="download-text text-#1A5FA9 underline-offset-4 mb-24rpx" @tap="handleDownloadFile">
              采购单合同&发货清单&箱单(三合一)
            </view>
            <view
              v-if="detail.poState !== 6 && detail.poState !== 7 && (detail.paymentSign === 1 || detail.paymentSign === 2) && detail.paymentType === 1"
              class="download-text text-#1A5FA9 underline-offset-4 mb-24rpx font-800" @tap="handlePreview">
              付款流水单
            </view>
            <view v-if="detail.poState !== 1">
              <!-- <view v-if="detail.poState !== 9 && detail.poState !== 8"
                class="download-text text-#1A5FA9 underline-offset-4">产品条形码</view> -->
              <!-- <view v-if="detail.poState === 9 || detail.poState === 8"
                class="download-text text-#1A5FA9 underline-offset-4" @tap="handleDownloadFile('付款单')">好达威付款单</view> -->
            </view>
          </view>
        </view>
        <view class="flex items-center">
          <view class="min-w-260rpx">回签合同：</view>
          <view>
            <view v-if="!detail.backContractUrl" class="text-#1A5FA9 text-24rpx">
              <up-upload
                v-if="detail.poState !== 7 && (detail.poState === 8 && detail.backContractType === 1 || detail.poState !== 8) && detail.poState !== 9"
                :fileList="fileList" accept="all" name="file" :maxCount="1" uploadText="点击上传"
                @afterRead="handleUploadChange">
                <up-button color="#1A5FA9" type="primary" size="mini" text="点击上传" shape="circle"></up-button>
              </up-upload>
              <view v-else class="text-24rpx text-#86909C">未上传</view>
            </view>
            <view v-else>
              <view v-if="detail.backContractUrl.split('.').pop() === 'pdf'" class="text-#1A5FA9 flex items-center">
                <span class="underline-offset-4 underline mr-30rpx"
                  @click="() => downFile(detail.backContractUrl)">回签合同文件.{{
                    detail.backContractUrl.split('.').pop() }}</span>
                <u-icon
                  v-if="detail.poState !== 7 && (detail.poState === 8 && detail.backContractType === 2 || detail.poState !== 8) && detail.poState !== 9"
                  name="close" @click="handleDeleteFile"></u-icon>
              </view>
              <view v-else class="w-110rpx h-110rpx mr-10rpx mb-10rpx relative overflow-hidden border-rd-10rpx">
                <img style="width: 110rpx; height: 110rpx;" class="border-rd-10rpx" :src="detail.backContractUrl"
                  @click="previewBackContract" />
                <!-- <up-album :urls="[detail.backContractUrl || defaultImg]"></up-album> -->
                <view
                  v-if="detail.poState !== 7 && (detail.poState === 8 && detail.backContractType === 2 || detail.poState !== 8) && detail.poState !== 9"
                  class="w-40rpx h-40rpx absolute -right-12rpx -top-10rpx " @click="handleDeleteFile">
                  <u-icon name="close-circle-fill" size="20" color="##babdc1"></u-icon>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view>
        <!-- 采购单详情 -->
        <view v-if="detail?.skuInfoList?.length" class="detail-box">
          <view class="detail-title">
            采购单产品详情
          </view>
          <view class="common-product-list" v-for="(item, idx) in detail?.skuInfoList" :key="idx">
            <view class="common-product-list-item">
              <view class="common-product-list-item-left">
                <img style="width: 80rpx; height: 80rpx; border-radius: 8rpx; margin-right: 16rpx;"
                  :src="item.skuImageUrl || defaultImg" @click="previewProduct(item)" />
                <view>
                  <view class="flex items-start">
                    <view class="name">
                      <view v-if="item?.purchaseType === 1" class="jz-tag">集</view>{{ item?.skuDescription || '' }}
                    </view>
                    <span
                      v-if="(detail.poState === 2 || detail.poState === 3 || detail.poState === 10) && (item.skuState === 8 || item.skuState === 9)"
                      :class="`font-800 px-10rpx py-4rpx  text-24rpx border-rd-11px text-white vertical-middle ${skuStateTextColorMap.get(item.skuState)}`">
                      {{ skuStateTextMap.get(item.skuState) }}</span>
                    <span v-if="item.skuState === 7"
                      :class="`font-800 px-10rpx py-4rpx  text-24rpx border-rd-11px text-white vertical-middle bgGray`">
                      已取消</span>
                  </view>
                  <view class="sub-name">
                    好达威SKU:{{ item.skuCode || '' }}
                  </view>
                  <view v-if="item.supplierSkuCodes?.filter((code: string) => !!code)?.length" class="sub-name">
                    商家SKU:{{ item.supplierSkuCodes.join(',') || '' }}
                  </view>
                  <view
                    v-if="(detail.poState === 4 || detail.poState === 5) && item.skuState !== 8 && item.skuState !== 9"
                    :class="`text-24rpx  ${skuStateTextColorMap.get(item.skuState)}`">
                    {{ skuStateTextMap.get(item.skuState) ? skuStateTextMap.get(item.skuState) :
                      `${item.storeCount} 个已入仓` }}
                  </view>
                  <view v-if="detail.poState === 6 && (item.skuState !== 8 || item.skuState !== 9)"
                    :class="`text-24rpx  ${skuStateTextColorMap.get(item.skuState)}`">
                    已通过：{{ item.passCount }}，已取消：{{ item.cancelCount }}
                  </view>
                </view>
              </view>
              <view class="common-product-list-item-right">
                <view v-if="item.originSkuPcs !== item.skuPcs || item.originSkuUnitPrice !== item.skuUnitPrice"
                  class="line-through">{{ detail.poCurrency?.unitSymbol }}{{
                    thousandSeparatFormat(item.originSkuUnitPrice || 0) }}x{{
                    item?.originSkuPcs || 0 }}</view>
                <view>{{ detail.poCurrency?.unitSymbol }}{{ thousandSeparatFormat(item?.skuUnitPrice || 0) }}x{{
                  item?.skuPcs || 0
                }}</view>
                <view class="greenText font-700"
                  v-if="(detail.poState === 2 || detail.poState === 3 || detail.poState === 10 || detail.poState === 11) && item.deliveryCount > 0">
                  （已发{{ item.deliveryCount }}）
                </view>
              </view>
            </view>
            <view style="margin-bottom: 24rpx;" class="text-#6B7280 text-24rpx">
              {{ item?.skuRemark || '' }}
            </view>
          </view>
          <view class="font-700 text-14px text-right">
            总金额：{{ detail.poCurrency?.unitSymbol }}{{ thousandSeparatFormat(detail?.poPrice || 0) }}
          </view>
        </view>
        <!-- 发货详情 -->
        <view
          v-if="detail?.deliveryInfoList?.length && detail.poState !== 1 && detail.poState !== 2 && detail.poState !== 6 && detail.poState !== 9"
          class="detail-box ">
          <view class="detail-title">
            发货详情
          </view>
          <view v-for="(pack, packKey) in detail?.deliveryInfoList" :key="packKey">
            <view class="font-600 text-24rpx text-#4E5969 mb-10rpx">包裹{{ packKey + 1 }}</view>
            <view class="flex justify-between mb-30rpx">
              <view class="text-#1A5FA9 font-800 text-24rpx ">{{ pack?.expressNumber || '' }}</view>
              <view class="text-#6B7280 text-24rpx">{{ pack?.createdTime || '' }}</view>
            </view>
            <view class="common-product-list" v-if="pack?.skuInfoList?.length" v-for="(item, idx) in pack?.skuInfoList"
              :key="idx">
              <view class="common-product-list-item">
                <view style="margin-bottom: 30rpx;" class="common-product-list-item-left ">
                  <img style="width: 80rpx; height: 80rpx; border-radius: 8rpx; margin-right: 16rpx;"
                    :src="item.skuImageUrl || defaultImg" @click="previewDelivery(item)" />
                  <view>
                    <view class="name">
                      {{ item?.skuDescription || '' }}
                    </view>
                    <view class="sub-name">
                      好达威SKU:{{ item.skuCode || '' }}
                    </view>
                    <view v-if="item.supplierSkuCodes?.filter((code: string) => !!code)?.length" class="sub-name">
                      商家SKU:{{ item.supplierSkuCodes.join(',') || '' }}
                    </view>
                  </view>
                </view>
                <view class="common-product-list-item-right">数量：{{ item?.deliveryCount || 0 }}</view>
              </view>
            </view>
            <view class="mb-20rpx">
              <view v-if="pack.expressRemark" class="text-#6B7280 text-28rpx flex">
                <view class="w-140rpx">发货备注：</view>
                <view class="remark">{{ pack.expressRemark }}</view>
              </view>
              <view v-if="pack.expressFeedbackUrlList?.length" class="text-#6B7280 text-28rpx flex">
                <view class="w-140rpx">备注图片：</view>
                <view class="remark remark-img">
                  <u-album :urls="pack.expressFeedbackUrlList"></u-album>
                </view>
              </view>
            </view>
            <view v-if="pack?.deliveryUrl"
              class="text-#1A5FA9 font-800 text-24rpx mb-20rpx underline underline-offset-4"
              @tap="() => downFile(pack?.deliveryUrl)">
              下载发货清单（必须随货一份）
            </view>
          </view>
        </view>
        <view
          v-if="detail.logs?.length && detail.poState !== 6 && detail.poState !== 7 && detail.poState !== 9 && dayjs(detail.createdTime).isAfter(dayjs('2024-09-20 18:00:00'))">
          <view class="detail-title">
            采购单状态追踪
          </view>
          <!-- log.operateTime -->
          <up-steps :current="currentLog.toString()" direction="column" activeColor="#1A5FA9" dot :key="stepTime">
            <up-steps-item v-for="(log, index) in detail.logs" :key="index.toString() + stepTime"
              :title="log.operateTime" :desc="log.operateDesc" :class="log.isGray ? 'gray' : ''">
            </up-steps-item>
          </up-steps>
        </view>
        <view v-if="detail?.poChangeRecord?.length">
          <view class="detail-title mt-10rpx">
            变更记录
          </view>
          <view v-for="change in detail?.poChangeRecord" :key="change.messageChangeTime" class="mb-30rpx">
            <view class="text-#6B7280 mt-10rpx">{{ change.messageChangeTime }}</view>
            <view v-for="item in change.poChangeRecordDetail" :key="item.poSkuId">
              <view class="common-product-list-item" style="margin-bottom: 0;">
                <view class="common-product-list-item-left ">
                  <img style="width: 80rpx; height: 80rpx; border-radius: 8rpx; margin-right: 16rpx;"
                    :src="item.skuImageUrl || defaultImg" @click="previewChange(item)" />
                  <view>
                    <view class="name">
                      {{ item?.skuDescription || '' }}
                    </view>
                    <view class="sub-name">
                      好达威SKU:{{ item.skuCode || '' }}
                    </view>
                    <view v-if="item.supplierSkuCodes?.filter((code: string) => !!code)?.length" class="sub-name">
                      商家SKU:{{ item.supplierSkuCodes.join(',') || '' }}
                    </view>
                  </view>
                </view>
                <view v-if="item.skuChangeDesc?.length > 0">
                  <view v-for="(desc, index) in item.skuChangeDesc" :key="index"
                    class="wax-w-200rpx text-black font-700 text-24rpx">
                    {{ desc }}</view>
                </view>
              </view>
              <view class="text-#6B7280 text-24rpx">{{ item.notes }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view>
      <view v-if="detail.poState === 1" class="h-148rpx w-full box-border items-center justify-between py-26rpx flex">
        <view class="w-318rpx mr-20rpx ">
          <up-button class="left-btn" iconColor="#000" color="#1D2129" type="primary" :plain="true" :hairline="true"
            text="更改信息" @click="gotoUpdate"></up-button>
        </view>
        <view class="w-318rpx">
          <up-button class="right-btn w-298rpx" color="#1A5FA9" type="primary" text="确认订单"
            @click="handleConfirm"></up-button>
        </view>
      </view>
      <view v-if="detail.poState === 2 || detail.poState === 3 || detail.poState === 10 || detail.poState === 11"
        class="h-148rpx w-full box-border items-center justify-around flex py-26rpx">
        <up-button color="#1A5FA9" type="primary" text="发货" @click="gotoDelivery"></up-button>
      </view>
    </view>
  </view>

  <u-popup :show="confirmShow" mode="bottom" >
    <view>
        <view class="cofirmHeader flex justify-center font-bold p-16rpx font-size-36rpx" style="border-bottom: 1rpx rgba(180, 180, 180, 0.7) solid;">
          是否确认订单
        </view>

        <view class=" p-16rpx">
          确认之后该订单状态将更新为【待发货】，请前往“待发货”查看并处理发货。<br />
          是否确认订单？
        </view>

        <view class=" p-16rpx" style="background:rgba(255, 230, 202, 0.6);">
          <view class="color-#FFA035 flex">
            <u-icon name="info-circle-fill" color="#FFA035" size="28"></u-icon> 发货地址提醒
          </view>
          <view class="color-#FFA035">
            本采购单收货地址为<text class="font-bold color-red">「华南仓-东莞」</text>，请按照采购单对应的收货地址进行发货
          </view>
        </view>

        <view class="flex ">
          <up-button class="w-50%"  text="取消" @click="confirmShow = false"></up-button>
          <up-button class="w-50%" color="#1A5FA9" type="primary" text="确认订单"
            @click="orderConfirm"></up-button>
        </view>
    </view>
	</u-popup>
</template>

<script setup lang="ts">
import { poManageQueryPoDetail } from "@/genapi/poManage"
import { supplierPoApprovalOrderConfirm } from "@/genapi/supplierPoApproval"
import { onLoad } from '@dcloudio/uni-app'
import dayjs from "dayjs"
import duration from "dayjs/plugin/duration"
import { stateMap, poStateBgColorMap, poStateTipMap, skuStateTextColorMap, skuStateTextMap } from "@/utils/options"
import { orderAttachmentDownload } from "@/genapi/_supplier"
import { thousandSeparatFormat } from "@/utils/utils"
import { useSupplierStore } from '@/store/index'
import { originStatusList } from "@/utils/options"
import defaultImg from "@/static/default.png"
import { poManageBackContractDelete } from "@/genapi/poManage"
const fileList = ref([])
const stepTime = ref(new Date().getTime())
const supplierStore = useSupplierStore()
let detailId = ''
let isGZStore = false
let currentLog = ref('0')
const detail = ref({})
const confirmShow = ref(false)
const countdownStr = ref('00: 00: 00')
const isPreviewProduct = ref(false)
const isPreviewDelivery = ref(false)
const isPreviewChange = ref(false)
const isPreviewBackContract = ref(false)
const previewProductImage = ref()
const previewDeliveryImage = ref()
const previewChangeImage = ref()
const previewBackContractImage = ref()
const currentRecord = ref({})
dayjs.extend(duration);
function countdown(endTime: any, selector: string) {
  const now: any = dayjs();
  const durationToEnd = dayjs.duration(endTime - now, 'milliseconds');
  if (durationToEnd.asMilliseconds() > 0) {
    let minutes: any = durationToEnd.minutes();
    let seconds: any = durationToEnd.seconds();
    minutes = minutes < 10 ? `0${minutes}` : minutes
    seconds = seconds < 10 ? `0${seconds}` : seconds
    // 更新页面上的倒计时显示
    countdownStr.value = `${minutes}: ${seconds}`;
    // 递归调用函数，每秒更新一次
    setTimeout(() => {
      countdown(endTime, selector);
    }, 1000);
  } else {
    // 倒计时结束，清除定时器
    countdownStr.value = '00: 00'
  }
}
// 使用方法：endTime是倒计时结束时的时间，selector是页面上显示倒计时的元素的ID
onLoad((query) => {
  detailId = query?.id || ''
  uni.setTabBarItem({
    index: 0,
    iconfont: {
      "text": "\ue102",
      "selectedText": "\ue103",
      "fontSize": "17px",
      "color": "#000000",
      "selectedColor": "#0000ff"
    },
    fontSize: '16px',
    background: '#ffffff',
    border: 'none',
  });
})

function handleConfirm(){
  if(detail.value.poRemindType){
    confirmShow.value = true
  }else{
    orderConfirm()
  }
}
// 预览产品图片
async function previewProduct(item: any) {
  currentRecord.value = item
  isPreviewProduct.value = true
  await nextTick(() => {
    previewProductImage.value.open(item.skuImageUrl); // 传入当前选中的图片地址(小程序必须添加$nextTick，解决组件首次加载无图)
  })
};
// 预览发货图片
async function previewDelivery(item: any) {
  currentRecord.value = item
  isPreviewDelivery.value = true
  await nextTick(() => {
    previewDeliveryImage.value.open(item.skuImageUrl); // 传入当前选中的图片地址(小程序必须添加$nextTick，解决组件首次加载无图)
  })
}
// 预览变更图片
async function previewChange(item: any) {
  currentRecord.value = item
  isPreviewChange.value = true
  await nextTick(() => {
    previewChangeImage.value.open(item.skuImageUrl); // 传入当前选中的图片地址(小程序必须添加$nextTick，解决组件首次加载无图)
  })
}
// 预览回签合同图片
async function previewBackContract() {
  isPreviewBackContract.value = true
  await nextTick(() => {
    previewBackContractImage.value.open(detail.value.backContractUrl); // 传入当前选中的图片地址(小程序必须添加$nextTick，解决组件首次加载无图)
  })
}
// 跳转更改货期与降价
function gotoUpdate() {
  uni.navigateTo({
    url: `/pages/updateOrder/index?id=${detailId}`
  })
}
// 跳转填写货期
function gotoUpdateDay() {
  uni.navigateTo({
    url: `/pages/updateDay/index?id=${detailId}`
  })
}
// 跳转发货
function gotoDelivery() {
  uni.navigateTo({
    url: `/pages/deliverGoods/index?id=${detailId}&isGZStore=${isGZStore}`,
  })
}
// 订单确认
async function orderConfirm() {
  const deliveryDaysVaild = detail.value?.skuInfoList?.length && detail.value?.skuInfoList.every(item => !!item.deliveryDays)
  if (!deliveryDaysVaild) {
    uni.showToast({
      title: '货期为空，请先填写货期',
      icon: 'none'
    })
    gotoUpdateDay()
    return
  }
  const params: any = { poOrderId: detailId }
  const { data } = await supplierPoApprovalOrderConfirm(params)
  if (data?.code !== 200) {
    return
  }else {
    confirmShow.value = false

    uni.showToast({
      title: '订单已确认,请及时发货',
      icon: 'success'
    })
    getDetail()
  }
}
function handleLogData(curLogStatus: number) {
  const statusList = [...originStatusList]
  const index = statusList.findIndex(item => item.curLogStatus === curLogStatus)
  if (index !== -1) {
    statusList.splice(0, index + 1)
  }
  return [...statusList]
}
async function getDetail() {
  const { data } = await poManageQueryPoDetail({ id: detailId })
  if (data?.code !== 200) return
  Object.assign(detail.value, data.data)
  isGZStore = detail.value.storeName?.includes('广州')
  if (detail.value.poStatusChangeLogs?.length) {
    const lastPartList = handleLogData(detail.value.curLogStatus)
    detail.value.logs = [...detail.value.poStatusChangeLogs, ...lastPartList]
    currentLog.value = detail.value.poStatusChangeLogs.length - 1
  } else {
    detail.value.logs = originStatusList
    currentLog.value = '0'
  }
  detail.value.poStateBgColor = (poStateBgColorMap.get(data.data.poState)) || 'text-#6B7280'
  detail.value.poStateTip = (poStateTipMap.get(data.data.poState)) || ''
  // 启用倒计时
  if (detail.value.poState === 1 && detail.value.createdTime) {
    const endTime: any = dayjs(detail.value.createdTime).add(30, 'minute')
    countdown(dayjs(endTime), 'countdown');
  }
  console.log(detail.value)
  nextTick()
}
// 上传回签合同
async function handleUploadChange(file: any) {
  const fileType = file.file.url.split('.').pop().toLowerCase()
  const typeList = ['pdf', 'png', 'jpg', 'jpeg']
  if (!typeList.includes(fileType)) {
    setTimeout(() => {
      uni.showToast({
        title: '请上传pdf、png、jpg、jpeg文件',
        icon: 'none'
      })
    }, 200)
    return
  }
  setTimeout(() => {
    uni.showLoading({
      title: '上传中...',
      mask: true,
    })
  }, 200)
  uni.uploadFile({
    url: `${import.meta.env.VITE_BASE_API_URL}/api/poManage/backContractUpload`,
    filePath: file.file.url,
    name: 'file',
    header: {
      Authorization: 'Bearer ' + uni.getStorageSync('token')
    },
    formData: {
      poId: detailId
    },
    success: (res) => {
      uni.hideLoading()
      const data = JSON.parse(res.data)
      if (data?.code !== 200) {
        uni.showToast({
          title: data?.msg || '上传失败',
          icon: 'none'
        })
      } else {
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        })
        getDetail()
      }
    },
    fail: (error) => {
      uni.hideLoading()
      console.error('上传文件失败', error);
    }
  })
}

// 删除回签合同
async function handleDeleteFile() {
  console.log('删除回签合同')
  const { data } = await poManageBackContractDelete({ poId: detailId })
  if (data?.code !== 200) return
  else {
    uni.showToast({
      title: '删除成功',
      icon: 'success'
    })
    getDetail()
  }
}
async function handleDownloadFile(name = '采购单') {
  // let aa = uni.getFileSystemManager()
  // uni.downloadFile()
  const { data } = await orderAttachmentDownload({ orderId: detailId })
  // if(!data.code){
  const fs = uni.getFileSystemManager();
  let dt = new Date().getTime()

  fs.writeFile({
    //这里填文件的名字
    filePath: wx.env.USER_DATA_PATH + `/${name}${dt}.xlsx`,
    data: data,
    encoding: "binary",
    success(res) {
      uni.openDocument({
        showMenu: true,
        filePath: wx.env.USER_DATA_PATH + `/${name}${dt}.xlsx`,
        success: function (res) {
          console.log('打开文档成功');
        }
      });
    }
  })
  // }
}
// 下载发货清单/回签合同
async function downFile(url: string) {
  uni.showLoading({
    title: '加载中...'
  })
  uni.downloadFile({
    url,
    success: (res) => {
      uni.hideLoading()
      if (res.statusCode === 200) {
        uni.openDocument({
          filePath: res.tempFilePath,
          fileType: url.split('.').pop()
        });
      } else {
        console.error('下载文件失败');
      }
    },
    fail: (error) => {
      uni.hideLoading()
      console.error('下载文件失败', error);
    }
  });
}
// 预览付款流水单
function handlePreview() {
  const urls = detail.value?.paymentUrlList
  if (urls?.length) {
    uni.previewImage({
      current: urls[0] || '',
      urls,
    })
  }
}
onShow(async () => {
  stepTime.value = new Date().getTime()
  await getDetail()
  // 自定义导航栏
  uni.setNavigationBarTitle({
    title: detail.value.poNumber // 页面标题为"自定义标题"
  });
})
</script>

<style lang="scss" scoped>
.order-detail-page {
  .detail-box {
    padding: 16px 0;
  }

  .detail-border {
    border-bottom: 1px solid #E0E3E1;
  }

  .order-state {
    color: #fff;
    font-weight: 800;
    font-size: 24rpx;
  }

  .download-text {
    text-decoration: underline;
  }

}
.jz-tag{
  width: 40rpx;
  height: 40rpx;
  display: inline-block;
  border-radius: 50%;
  background: #fff;
  border: 1px solid #e50000;
  color: #e50000;
  text-align: center;
  margin-right: 4px;
}
</style>
